package cn.itcast.server;

import cn.itcast.protocol.MessageCodecSharable;
import cn.itcast.protocol.ProtocolFrameDecoder;
import cn.itcast.server.handler.*;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class ChatServer {
    public static void main(String[] args) {
        extracted();
    }

    private static void extracted() {
        int readerIdleTimeSeconds = 120;
        NioEventLoopGroup boss = new NioEventLoopGroup();
        NioEventLoopGroup worker = new NioEventLoopGroup();
        //netty提供的日志处理器
        LoggingHandler LOGGING_HANDLER = new LoggingHandler(LogLevel.DEBUG);
        //自定义的消息编码解码器，结合ProtocolFrameDecoder使用
        MessageCodecSharable MESSAGE_CODEC = new MessageCodecSharable();
        //登录请求处理器
        LoginRequestMessageHandler LOGIN_HANDLER = new LoginRequestMessageHandler();
        //聊天请求处理器
        ChatRequestMessageHandler CHAT_HANDLER = new ChatRequestMessageHandler();
        //建群请求处理器
        GroupCreateRequestMessageHandler GROUP_CREATE_HANDLER = new GroupCreateRequestMessageHandler();
        //加群请求处理器
        GroupJoinRequestMessageHandler GROUP_JOIN_HANDLER = new GroupJoinRequestMessageHandler();
        //查询群成员请求处理器
        GroupMembersRequestMessageHandler GROUP_MEMBERS_HANDLER = new GroupMembersRequestMessageHandler();
        //退群请求处理器
        GroupQuitRequestMessageHandler GROUP_QUIT_HANDLER = new GroupQuitRequestMessageHandler();
        //群聊请求处理器
        GroupChatRequestMessageHandler GROUP_CHAT_HANDLER = new GroupChatRequestMessageHandler();
        //退出请求处理器
        QuitHandler QUIT_HANDLER = new QuitHandler();
        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.channel(NioServerSocketChannel.class);
            serverBootstrap.group(boss, worker);
            //初始化以恶
            serverBootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
                @Override
                protected void initChannel(SocketChannel ch) {
                    ChannelPipeline pipeline = ch.pipeline();
                    pipeline.addLast(LOGGING_HANDLER); //日志
                    pipeline.addLast(new ProtocolFrameDecoder()); // 拆包解码器
                    pipeline.addLast(MESSAGE_CODEC); //自定义的消息编解码器
                    // 用来判断是不是 读空闲时间过长，或 写空闲时间过长，30s 内如果没有收到 channel 的数据，会触发一个 IdleState#READER_IDLE 事件
                    pipeline.addLast(new IdleStateHandler(readerIdleTimeSeconds, 0, 0));
                    pipeline.addLast(new ChannelDuplexHandler() { // ChannelDuplexHandler 可以同时作为入站和出站处理器
                        // 用来触发特殊事件
                        @Override
                        public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                            IdleStateEvent event = (IdleStateEvent) evt;
                            // 触发了读空闲事件
                            if (event.state() == IdleState.READER_IDLE) {
                                log.debug("已经 "+readerIdleTimeSeconds+"s 没有读到数据了,关闭channel");
                                ctx.channel().close();
                            }
                        }
                    });
                    pipeline.addLast(LOGIN_HANDLER);
                    pipeline.addLast(CHAT_HANDLER);
                    pipeline.addLast(GROUP_CREATE_HANDLER);
                    pipeline.addLast(GROUP_JOIN_HANDLER);
                    pipeline.addLast(GROUP_MEMBERS_HANDLER);
                    pipeline.addLast(GROUP_QUIT_HANDLER);
                    pipeline.addLast(GROUP_CHAT_HANDLER);
                    pipeline.addLast(QUIT_HANDLER);
                }
            });
            Channel channel = serverBootstrap.bind(8080).sync().channel();
            channel.closeFuture().sync();
        } catch (InterruptedException e) {
            log.error("server error", e);
        } finally {
            boss.shutdownGracefully();
            worker.shutdownGracefully();
        }
    }




}
